package com.health.service.impl;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.health.domain.dto.MemberLoginDTO;
import com.health.domain.pojo.Member;
import com.health.domain.vo.Result;
import com.health.mapper.MemberMapper;
import com.health.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author ghy
 * @version 1.0
 * @since 2025-06-24 10:03
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Autowired
    private MemberMapper memberMapper;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Result<Member> login(MemberLoginDTO memberLoginDTO) {
        String telephone = memberLoginDTO.getTelephone();
        String validateCode = memberLoginDTO.getValidateCode();
        // 1.比对验证码
        String redisCode = stringRedisTemplate.opsForValue().get("member_login_code_" + telephone);
        if(!StrUtil.equals(redisCode, validateCode)) {
            throw new RuntimeException("验证码错误！");
        }
        // TODO 从Redis中删除验证码
        stringRedisTemplate.delete("member_login_code_" + telephone);
        // 2.根据手机号查询会员信息
        // 3.如果会员不存在，则完成自动注册功能
        Member member = memberMapper.selectByPhoneNumber(telephone);
        if(ObjUtil.isNull(member)) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            memberMapper.insert(member);
        }
        // 4.返回信息
        // 数据脱敏
        member.setPassword("");
        return Result.success(member);
    }
}
